<?php
header("Content-type: application/json; charset:UTF-8");

if ($_POST['fname']!='') {
	if ($_POST['contents']!='') $arr=create_sub ($_POST['fname'], $_POST['contents']);
	else $arr=array("successful"=>"false", "message"=>"Your subtitles are empty!");
	
	die (json_encode($arr));
}


if (is_executable($_FILES['subtitle']['tmp_name'])) {
	$arr=array("successful" => "false" , "message" => "File not acceptable.");
	die (json_encode ($arr));
}
if (!file_get_contents($_FILES['subtitle']['tmp_name'])) {
	$arr=array("successful" => "false" , "message" => "File not readable.");
	die (json_encode ($arr));
}

if ($_FILES['subtitle']['size']>500000) {
	$arr=array("successful" => "false" , "message" => "Your file is too big!");
	die (json_encode ($arr));
}

$fname=$_FILES['subtitle']['name'];
$contents=file_get_contents ($_FILES['subtitle']['tmp_name']);

$res=create_sub($fname, $contents);

echo $res;

function create_sub ($fname, $contents) {

$subs_dir="../files";

$ext=substr($fname, -4);
if ($ext!=".srt") {
	$arr=array("successful" => "false" , "message" => "Only .srt (SubRip) files are supported by now.");
	return json_encode ($arr);
}

//$enc=mb_detect_encoding($contents);
//if ($enc=='UTF-8') $enc='Windows-1253';
//mb_convert_encoding($contents, "UTF-8", "ISO-8859-13");
$contents = iconv('Windows-1253','UTF-8//IGNORE', $contents);
//$contents = rmBOM($contents);


//die ($contents);

$num=rand(1,4);
$folder=rnd_alph($num);

while (is_dir($subsdir.'/'.$folder)) {
	$num=rand(1,4);
	$folder=rnd_alph($num);
}

mkdir ($subs_dir.'/'.$folder);
file_put_contents ($subs_dir.'/'.$folder.'/'.$fname, $contents);

$arr=array("successful" => "true", "id" => $folder, "name" => $fname);
return json_encode ($arr);
}

function rmBOM($str=""){
        if(substr($str, 0,3) == pack("CCC",0xef,0xbb,0xbf)) {
                $str=substr($str, 3);
        }
        return $str;
}

function rnd_alph ($length=4) {
$characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
$string = '';
for ($i = 0; $i < $length; $i++) {
	$string .= $characters[rand(0, strlen($characters) - 1)];
}
return $string;
}
?>
